package com.topisv.tms.web.stock;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.stock.CusStock;
import com.topisv.tms.entity.stock.ViewCusStock;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.stock.CusStockService;
import com.topisv.tms.service.stock.ViewCusStockService;
import com.topisv.tms.tools.ExcelStUtil;
import com.topisv.tms.tools.ExcelUtils;
import com.topisv.tms.utils.JsonUtil;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * 商家库存_control
 * @author ch
 *
 */
@Controller
@RequestMapping(value = "/cusStock")
public class CusStockController extends BaseDataTableController{
	
	@Autowired
	private ViewCusStockService viewCusStockService;
	@Autowired
	private CusStockService cusStockService;
	@Autowired
	private CustomersService customersService;
	
	private static final Logger logger = LoggerFactory.getLogger(CusStockController.class);

	/**
	 * 查询SKU
	 * @param pageNumber
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "query_viewCusStock",method = RequestMethod.POST)
	public void query_viewCusStock(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			QueryParamHolder paramHolder = collectParam(paramJson, "_");
			Map<String, Object> param = paramHolder.getSearchParams();
			Map<String, String> paramMap = paramHolder.getParamMap();
			String customerCode = (String) param.get("EQ_customer.customerCode");
			String warehouseCode = (String) param.get("EQ_warehouseCode");
			if(StringUtils.isBlank(customerCode)){
				String customerCodes=this.customersService.loadCustomerByAuthority(curUser.jobuuid);
				paramMap.put("customerCodes", StringUtils.isBlank(customerCodes)?"blank":customerCodes);
			}else{
				paramMap.put("customerCodes", customerCode);
			}
			if(StringUtils.isBlank(warehouseCode)){
				paramMap.put("areagroups", curUser.areagroups);
			}else{
				paramMap.put("areagroups", warehouseCode);
			}
			Page<ViewCusStock> page = viewCusStockService.loadViewStock(paramHolder);
			for (ViewCusStock viewCusStock : page.getContent()) {
				viewCusStockService.setDetail(viewCusStock);
			}
			response.getWriter().print(bulidJSON(page));
		} catch (IOException e) {
			log.error("some error happed.",e);
		}
	}
	
	/**
	 * 查询库位
	 * @param pageNumber
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "query_cusStock",method=RequestMethod.POST)
	public void query_cusStock(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response) {
		try {
			QueryParamHolder paramHolder = collectParam(paramJson, "_");
			Page<CusStock> page = cusStockService.findCusStock(paramHolder);
			for (CusStock cusStock : page.getContent()) {
				cusStockService.setDetail(cusStock);
			}
			response.getWriter().print(bulidJSON(page));
		} catch (IOException e) {
			log.error("some error happed.",e);
		}
	}
	
	
	@RequestMapping(value = "v2_show")
	public String query(Model model) {
		//查出当前用户关联的商家列表
		fillSelectValue(model, null);
		return "customer/stock/cusStock";
	}
	
	@RequestMapping(value = "stockDetail")
	public String stockDetail(ServletRequest request,HttpServletResponse response) {
		try {	
			
			String customerCode=request.getParameter("customerCode");
			String warehouseCode=request.getParameter("warehouseCode");
			String sku=request.getParameter("sku");
			List<CusStock> stockList=this.cusStockService.loadStockByCondition(customerCode,warehouseCode,sku);
			
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("stockList", stockList);
			String json = JsonUtil.getObjectString(map);
			
			PrintWriter out;
			out = response.getWriter();
			out.print(json);
		
		} catch (Exception e) {
			logger.error("error",e);
		}
		return null;
	}
	
	
	/**
	 * 导出库存信息_sku
	 */
	@RequestMapping(value = "exp_sku")
	public String exp_sku(Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//查询数据
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
			String warehouseCode=(String) searchParams.get("EQ_warehouseCode");
			String sku=(String) searchParams.get("LIKE_sku");
			String customerCode=(String) searchParams.get("EQ_customer.customerCode");
			if(StringUtils.isBlank(customerCode)){
				ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
				customerCode=this.customersService.loadCustomerByAuthority(curUser.jobuuid);
			}
			
			// begin remove 改用SQL 进行查询 20160601 lianghe.yuan
			/*Map<String, Object> param=new HashMap<String, Object>();
			param.put("customerCode", customerCode);
			param.put("warehouseCode", warehouseCode);
			param.put("sku", sku);
			
			List<ViewCusStock> infoList=this.viewCusStockService.loadByParam(param);
			
			*//** 定义导出数据集合 *//*
			List<Object[]> list = new ArrayList<Object[]>();
			
			for (int i = 0; i < infoList.size(); i++) {
				try {
					ViewCusStock o=infoList.get(i);
					Object[] obj = {
							i+1,
							o.getCustomer().getCustomerName(),
							o.getWarehouse().getGroupName(),
							o.getSku(),
							o.getBar(),	
							o.getGoodsName(),
							o.getSalesNum(),
							o.getUnusedNum(),
							o.getOrderNum(),
							o.getLockedNum(),
							o.getTransportNum(),
							o.getAirNum(),
							o.getTotalNum(),
						    null
					};
					list.add(obj);
				} catch (Exception e) {
					
					logger.error("error",e);
				}
			}*/

			List<Object[]> list = new ArrayList<Object[]>();
			
			if (StringUtils.isNotBlank(customerCode)) {
			    String[] customerCodes = customerCode.split(":");
			    List<String> clist = Arrays.asList(customerCodes);
			    
			    list = viewCusStockService.exportStockBySku(clist, warehouseCode, sku);
			}
			// begin remove 改用SQL 进行查询 20160601 lianghe.yuan
			
			if (StringUtils.isBlank(warehouseCode)) {
			    warehouseCode = "all"; //文件名处理
			}

			// modify 当数据超过6W行时，ExcelUtils.writeExcel(...) 不支持且报错，改用字符串模板引擎处理
			if (list.size() > 60000) {
			    response.setContentType("application/octet-stream");
                String fileName = new String((warehouseCode + "_库存明细.xls").getBytes("GBK"), "ISO8859-1");
                ((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename=" + fileName);
                
                String[] titles = { "序号", "商家","仓库","SKU","货号","商品名","可销售库存","不可销售库存","订单占用库存","锁定库存","调拨占用库存","调拨中库存","库存总量"};
                String pageTitle="库存明细";
                
                ExcelStUtil.export(response.getOutputStream(), DateFormatUtils.format(now, "yyyyMMddhhmmss"), pageTitle, titles, list);
			} else {
    			/** 导出数据 */
    			String[] title = { "序号", "商家","仓库","SKU","货号","商品名","可销售库存","不可销售库存","订单占用库存","锁定库存","调拨占用库存","调拨中库存","库存总量"};
    			String filepath =warehouseCode+".xls";
    			String title_page="库存明细";
    			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
    			/** 把生成的excel文件读出字节返回给客户端 */
    			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"utf-8"));
    			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
    			byte[] fb = new byte[f.available()];
    			f.read(fb);
    			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
    			output =((HttpServletResponse)response).getOutputStream();
    			int by = 0;
    			while ((by = bais.read()) != -1) {
    				output.write(by);
    			}
    			output.flush();
			}
			
		} catch (Exception e) {
			logger.error("", e);
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	
	
	/**
	 * 导出库存信息_bar
	 */
	@RequestMapping(value = "exp_bar")
	public String exp_bar(Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//查询数据
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
			String warehouseCode=(String) searchParams.get("EQ_warehouseCode");
			String bar=(String) searchParams.get("bar");
			String customerCode=(String) searchParams.get("EQ_customer.customerCode");
			if(StringUtils.isBlank(customerCode)){
				ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
				customerCode=this.customersService.loadCustomerByAuthority(curUser.jobuuid);
			}
			
			Map<String, Object> param=new HashMap<String, Object>();
			param.put("customerCode", customerCode);
			param.put("warehouseCode", warehouseCode);
			param.put("bar", bar);
			
			List<ViewCusStock> infoList=this.viewCusStockService.loadByParam(param);
			
			/** 定义导出数据集合 */
			List<Object[]> list = new ArrayList<Object[]>();
			
			for (int i = 0; i < infoList.size(); i++) {
				try {
					ViewCusStock o=infoList.get(i);
					Object[] obj = {
							i+1,
							o.getCustomer().getCustomerName(),
							o.getWarehouse().getGroupName(),
							o.getSku(),
							o.getBar(),	
							o.getGoodsName(),
							o.getSalesNum(),
							o.getUnusedNum(),
							o.getOrderNum(),
							o.getLockedNum(),
							o.getTransportNum(),
							o.getAirNum(),
							o.getTotalNum(),
						    null
					};
					list.add(obj);
				} catch (Exception e) {
					
					logger.error("error",e);
				}
			}
			
			/** 导出数据 */
			String[] title = { "序号", "商家","仓库","SKU","货号","商品名","可销售库存","不可销售库存","订单占用库存","锁定库存","调拨占用库存","调拨中库存","库存总量"};
			String filepath =warehouseCode+".xls";
			String title_page="库存明细";
			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
			byte[] fb = new byte[f.available()];
			f.read(fb);
			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
			output =((HttpServletResponse)response).getOutputStream();
			int by = 0;
			while ((by = bais.read()) != -1) {
				output.write(by);
			}
			output.flush();
			
		} catch (Exception e) {
			
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	
	
	/**
	 * 导出库存信息_name
	 */
	@RequestMapping(value = "exp_name")
	public String exp_name(Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//查询数据
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
			String warehouseCode=(String) searchParams.get("EQ_warehouseCode");
			String name=(String) searchParams.get("name");
			String customerCode=(String) searchParams.get("EQ_customer.customerCode");
			if(StringUtils.isBlank(customerCode)){
				ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
				customerCode=this.customersService.loadCustomerByAuthority(curUser.jobuuid);
			}
			
			Map<String, Object> param=new HashMap<String, Object>();
			param.put("customerCode", customerCode);
			param.put("warehouseCode", warehouseCode);
			param.put("name", name);
			
			List<ViewCusStock> infoList=this.viewCusStockService.loadByParam(param);
			
			/** 定义导出数据集合 */
			List<Object[]> list = new ArrayList<Object[]>();
			
			for (int i = 0; i < infoList.size(); i++) {
				try {
					ViewCusStock o=infoList.get(i);
					Object[] obj = {
							i+1,
							o.getCustomer().getCustomerName(),
							o.getWarehouse().getGroupName(),
							o.getSku(),
							o.getBar(),	
							o.getGoodsName(),
							o.getSalesNum(),
							o.getUnusedNum(),
							o.getOrderNum(),
							o.getLockedNum(),
							o.getTransportNum(),
							o.getAirNum(),
							o.getTotalNum(),
						    null
					};
					list.add(obj);
				} catch (Exception e) {
					
					logger.error("error",e);
				}
			}
			
			/** 导出数据 */
			String[] title = { "序号", "商家","仓库","SKU","货号","商品名","可销售库存","不可销售库存","订单占用库存","锁定库存","调拨占用库存","调拨中库存","库存总量"};
			String filepath =warehouseCode+".xls";
			String title_page="库存明细";
			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
			byte[] fb = new byte[f.available()];
			f.read(fb);
			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
			output =((HttpServletResponse)response).getOutputStream();
			int by = 0;
			while ((by = bais.read()) != -1) {
				output.write(by);
			}
			output.flush();
			
		} catch (Exception e) {
			
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	
	
	/**
	 * 导出库存信息_stockCode
	 */
	@RequestMapping(value = "exp_stockCode")
	public String exp_stockCode(Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//查询数据
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
			String customerCode=(String) searchParams.get("EQ_customer.customerCode");
			String warehouseCode=(String) searchParams.get("EQ_warehouseCode");
			String stockCode=(String) searchParams.get("stockCode");
			if(StringUtils.isBlank(customerCode)){
				ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
				customerCode=this.customersService.loadCustomerByAuthority(curUser.jobuuid);
			}
			
			Map<String, Object> param=new HashMap<String, Object>();
			param.put("customerCode", customerCode);
			param.put("warehouseCode", warehouseCode);
			param.put("stockCode", stockCode);
			
			List<CusStock> infoList=this.cusStockService.findStockByParam(param);
			
			/** 定义导出数据集合 */
			List<Object[]> list = new ArrayList<Object[]>();
			
			for (int i = 0; i < infoList.size(); i++) {
				try {
					CusStock o=infoList.get(i);
					Object[] obj = {
							i+1,
							o.getCustomer().getCustomerName(),
							o.getWarehouse().getGroupName(),
							o.getSku(),
							o.getBar(),	
							o.getGoodsName(),
							o.getSalesNum(),
							o.getUnusedNum(),
							o.getOrderNum(),
							o.getLockedNum(),
							o.getTransportNum(),
							o.getAirNum(),
							o.getTotalNum(),
						    null
					};
					list.add(obj);
				} catch (Exception e) {
					
					logger.error("error",e);
				}
			}
			
			/** 导出数据 */
			String[] title = { "序号", "商家","仓库","SKU","货号","商品名","可销售库存","不可销售库存","订单占用库存","锁定库存","调拨占用库存","调拨中库存","库存总量"};
			String filepath =warehouseCode+".xls";
			String title_page="库存明细";
			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
			byte[] fb = new byte[f.available()];
			f.read(fb);
			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
			output =((HttpServletResponse)response).getOutputStream();
			int by = 0;
			while ((by = bais.read()) != -1) {
				output.write(by);
			}
			output.flush();
			
		} catch (Exception e) {
			
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	
	/**
	 * 导出库存信息_boxCode
	 */
	@RequestMapping(value = "exp_boxCode")
	public String exp_boxCode(Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//查询数据
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
			String customerCode=(String) searchParams.get("EQ_customer.customerCode");
			String warehouseCode=(String) searchParams.get("EQ_warehouseCode");
			String boxCode=(String) searchParams.get("boxCode");
			if(StringUtils.isBlank(customerCode)){
				ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
				customerCode=this.customersService.loadCustomerByAuthority(curUser.jobuuid);
			}
			
			Map<String, Object> param=new HashMap<String, Object>();
			param.put("customerCode", customerCode);
			param.put("warehouseCode", warehouseCode);
			param.put("boxCode", boxCode);
			
			List<CusStock> infoList=this.cusStockService.findStockByParam(param);
			
			/** 定义导出数据集合 */
			List<Object[]> list = new ArrayList<Object[]>();
			
			for (int i = 0; i < infoList.size(); i++) {
				try {
					CusStock o=infoList.get(i);
					Object[] obj = {
							i+1,
							o.getCustomer().getCustomerName(),
							o.getWarehouse().getGroupName(),
							o.getStockCode(),
							o.getBoxCode(),
							o.getSku(),
							o.getBar(),	
							o.getGoodsName(),
							o.getSalesNum(),
							o.getUnusedNum(),
							o.getOrderNum(),
							o.getLockedNum(),
							o.getTransportNum(),
							o.getAirNum(),
							o.getTotalNum(),
						    null
					};
					list.add(obj);
				} catch (Exception e) {
					
					logger.error("error",e);
				}
			}
			
			/** 导出数据 */
			String[] title = { "序号", "商家","仓库","库位编码","箱子编码","SKU","货号","商品名","可销售库存","不可销售库存","订单占用库存","锁定库存","调拨占用库存","调拨中库存","库存总量"};
			String filepath =warehouseCode+".xls";
			String title_page="库存明细";
			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
			byte[] fb = new byte[f.available()];
			f.read(fb);
			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
			output =((HttpServletResponse)response).getOutputStream();
			int by = 0;
			while ((by = bais.read()) != -1) {
				output.write(by);
			}
			output.flush();
			
		} catch (Exception e) {
			
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	
}
